import { Injectable } from "@nestjs/common";
import { InjectDataSource, InjectEntityManager, InjectRepository } from "@nestjs/typeorm";
import { DataSource, EntityManager, Repository } from "typeorm";
import { User } from "../entity/User";

@Injectable()
export class UserService {
  @InjectEntityManager()
  private readonly manager: EntityManager;

  @InjectDataSource()
  private readonly dataSource: DataSource;

  constructor(
    @InjectRepository(User)
    private readonly userRepository: Repository<User>
  ) {}

  async create(userData: Partial<User>): Promise<User> {
    // return this.manager.save(User, userData);  
    // return this.manager.getRepository(User).save(userData);
    // return this.dataSource.getRepository(User).save(userData); 
    return this.userRepository.save(userData);
  }

  async findAll(): Promise<User[]> {
    //    return this.manager.findOne(User)
    return this.userRepository.find();
  }

  async findOne(id: number): Promise<User | null> {
    // return this.manager.findOneBy(User, {
    //   id,
    // });

    return this.userRepository.findOneBy({ id });
  }

  async update(id: number, userData: Partial<User>): Promise<User | null> {
    //   this.manager.save(User, {
    //   id: id,
    //   ...userData
    // })

    await this.userRepository.update(id, userData);
    return this.userRepository.findOneBy({ id });
  }

  async delete(id: number): Promise<void> {
    //this.manager.delete(User, id);
    await this.userRepository.delete(id);
  }
}
